<?php
class File
{
	private $_strFilename;
	private $_strCategoryName;
	private $_arrFile;
	private $_strTargetPath = 'tmp/';
	private $_strTemplatePath = 'templates/';
	private $_arrTemplates = array();
	
	public function __construct($arrFile, $strFilename)
	{
		$this->_arrFile = $arrFile;
		$this->_strFilename = $strFilename;
	}
	
	public function uploadFile()
	{
		$strFilename = basename( $this->_arrFile[$this->_strFilename]['name']);
		
		$this->_strCategoryName = $this->_getCategoryName($strFilename);
		
		$this->_strTargetPath = $this->_strTargetPath . $strFilename; 
		
		if(move_uploaded_file($this->_arrFile[$this->_strFilename]['tmp_name'], $this->_strTargetPath)) {
		    return true;
		} else{
		    return false;
		}
	}
	
	public function readCsvFile()
	{
	    $objFileHandle = fopen($this->_strTargetPath, "r");
	    
		if ($objFileHandle !== FALSE) {
			
			//create directory for the generated file
			//directory name is the category name
			$this->_createCategoryDirectory();
			
		    while ( ($arrData = fgetcsv($objFileHandle, 1000, ",")) !== FALSE) { //read per line
		        $this->_generateTemplate($arrData[0]);
		    }
		    fclose($objFileHandle);
		}
		
		//delete file
		$this->_deleteFile();
	}
	
	/**
	 * Private functions
	 */
	private function _createCategoryDirectory() 
	{
		mkdir('../'.$this->_strCategoryName, 0777);
	}

	private function _generateTemplate($strKeyword) 
	{
		if (!count($this->_arrTemplates)) { //so we only get the template files once
			$this->_getTemplateFiles();
		}

		$strTemplateFile = $this->_arrTemplates[array_rand($this->_arrTemplates)];

		$objFileHandle = fopen($this->_strTemplatePath . $strTemplateFile, "r");
		
		if ($objFileHandle !== FALSE) {
		    
		    //create file
		    $strFilePath = '../'. $this->_strCategoryName .'/'. $strKeyword .'.html';
		    $objTemplateFileHandle = fopen($strFilePath , "w");
		    
		    if ($objTemplateFileHandle !== FALSE) {
			    $strFileContent = fread($objFileHandle, filesize($this->_strTemplatePath . $strTemplateFile));
			    
			    //replace keywords
			    $strFileContent = str_replace('{{KEYWORD}}', $strKeyword, $strFileContent);
			    
		    	fwrite($objTemplateFileHandle, $strFileContent);
		    	fclose($objTemplateFileHandle);
		    }
		    
		    fclose($objFileHandle);
		}
	}
	
	private function _getTemplateFiles()
	{
	    foreach(scandir($this->_strTemplatePath) as $strFile) {
	        if(is_file($this->_strTemplatePath . $strFile)) {
	            array_push($this->_arrTemplates, $strFile);
	        }
	    }
	}
	
	private function _getCategoryName($strFilename)
	{
		$arrFilename = explode('.', $strFilename);
		
		return $arrFilename[0];
	}
	
	private function _deleteFile()
	{
		unlink($this->_strTargetPath);
	}
}